package service

import (
	"url-shortener/internal/storage"
	"url-shortener/internal/util"
)

type Service struct {
	storage storage.Storage
	config  *Config
}

type Config struct {
	ShortCodeLength int
}

func NewService(storage storage.Storage, cfg *Config) *Service {
	return &Service{
		storage: storage,
		config:  cfg,
	}
}

// ShortenURL 缩短URL
func (s *Service) ShortenURL(longURL string) (string, error) {
	// 检查URL是否已存在
	if shortCode, exists := s.storage.Exists(longURL); exists {
		return shortCode, nil
	}

	// 生成短码
	shortCode := util.GenerateShortCodeFromURL(longURL, s.config.ShortCodeLength)

	// 保存映射关系
	if err := s.storage.Save(longURL, shortCode); err != nil {
		return "", err
	}

	return shortCode, nil
}

// GetOriginalURL 获取原始URL
func (s *Service) GetOriginalURL(shortCode string) (string, error) {
	return s.storage.Get(shortCode)
}